/*
 * Copyright (C) 2009 Jiannan Lu
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */


package com.restsql.atom.util;

import com.restsql.atom.Content;
import com.restsql.atom.Entry;
import com.restsql.atom.Link;
import com.restsql.db.Database;
import com.restsql.util.collection.MultiValuedMap;
import com.sun.net.httpserver.HttpExchange;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.Attribute;
import javax.xml.stream.events.StartElement;
import javax.xml.stream.events.XMLEvent;
import restsql.Main;

/**
 *
 * @author L
 */
public class EntryUtil {

    public void EntryUtil() {
    }

    public static String DataToEntry(ResultSet rs, HttpExchange httpExchange, Database db) throws UnsupportedEncodingException, SQLException {
        String rqst_path = //URLDecoder.decode(
                httpExchange.getRequestURI().toString();//, "utf-8");

        String rootURL = Main.HOST_URL;

        String URL = rootURL + rqst_path;
        ResultSetMetaData rsmd = rs.getMetaData();

        int numberOfColumns = rsmd.getColumnCount();
        String[] ColumnNames = new String[numberOfColumns];
        String[] ColumnTypeNames = new String[numberOfColumns];
        String EntryTitle = "Entry";
        for (int i = 1; i <= numberOfColumns; i++) {
            ColumnNames[i - 1] = rsmd.getColumnName(i);
            ColumnTypeNames[i - 1] = rsmd.getColumnTypeName(i);
            EntryTitle = rsmd.getTableName(i);
        }
        int entry_count = 1;

        String Entry_id = "";
        Entry entry = null;
        while (rs.next()) {
            List contents = new ArrayList();
            List links = new ArrayList();
            entry = new Entry(Entry_id, EntryTitle);
            entry.setAuthors(db.getSchemaName());
            StringBuilder value = new StringBuilder();
            String SingleRsrcURL = URL;
            entry.setId(SingleRsrcURL);
            entry.setTitle(SingleRsrcURL);
            links.add(new Link("self", "application/atom+xml", SingleRsrcURL));
            links.add(new Link("edit", "application/atom+xml", SingleRsrcURL));
            for (int i = 1; i <= numberOfColumns; i++) {
                value.append("<" + ColumnNames[i - 1] + ">" + rs.getString(i) + "</" + ColumnNames[i - 1] + ">");
            }
            Content content = new Content();
            content.setValue(value.toString());
            contents.add(content);
            entry.setContents(contents);
            entry.setAlternateLinks(links);
            entry_count++;
        }
        if(entry == null){
            return "";
        }
        else{
            return "<?xml version='1.0' encoding='UTF-8'?>" + entry.toString();
        }
        
    }

    public static MultiValuedMap EntryStreamToValueSet(InputStream inS) throws XMLStreamException {

        MultiValuedMap values = new MultiValuedMap();

        XMLInputFactory inputFactory = XMLInputFactory.newInstance();
        InputStream in = inS;

        XMLEventReader eventReader = inputFactory.createXMLEventReader(in);

        boolean inEntry = false;
        boolean inContent = false;
        //Item currentItem = null;

        while (eventReader.hasNext()) {
            XMLEvent event = eventReader.nextEvent();

            if (event.isStartElement()) {
                StartElement startElement = event.asStartElement();


                if (event.asStartElement().getName().getLocalPart().equals("content")) {
                    inContent = true;
                    String key = "";
                    String value = "";
                     while(eventReader.hasNext()){
                         XMLEvent internal_event = eventReader.nextEvent();
                         if(internal_event.isStartElement()){                            
                             key = internal_event.asStartElement().getName().getLocalPart();
                             continue;
                         }
                         if(internal_event.isCharacters()){
                             String temp = internal_event.asCharacters().getData();
                             value = temp;
                             continue;
                         }
                         if(internal_event.isEndElement()){
                             if(internal_event.asEndElement().getName().getLocalPart().equals("content")){
                                 break;
                             }
                             values.add(key, value);
                             key = value = "";
                             continue;
                         }
                     }
                    continue;
                }
                if (event.asStartElement().getName().getLocalPart().equals("entry")) {
                    inEntry = true;
                    continue;
                }

            } else if (event.isEndElement()) {
                if (event.asEndElement().getName().getLocalPart().equals("entry")) {
                    inEntry = false;
                    continue;
                }
            }
        }
        return values;
    }
    
}